public class NM {
    //二叉搜索树的实现；
    //1.进行创建树；
    static class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode  right;
        public TreeNode(int val){
           this.val=val;
        }
    }
    public TreeNode root;//根节点；
    //2，进行查找某个节点；
    public TreeNode search(int key){
        TreeNode cur=root;
        while(cur!=null){
            if(cur.val<key){
                cur=cur.right;
            } else if (cur.val==key) {
                return cur;
            }else{
                cur=cur.left;
            }
        }
        return null;
    }
    //3，进行向二叉树中插入某个节点；
    public void insert(int key){
        if(root==null){
             root=new TreeNode(key);
        }
        TreeNode cur=root;
        TreeNode prev=null;
        TreeNode node=new TreeNode(key);
        while(cur!=null){
            if(cur.val<key) {
                prev=cur;
                cur = cur.right;
            } else if (cur.val==key) {
                return;//不能插入重复的节点；
            }else{
                prev=cur;
                cur=cur.left;
            }
        }
        if(prev.val<key) {
             prev.right=node;
        }else{
            prev.left=node;
        }
    }
    //3，进行删除一个结点；
    public void removeKey(int key){
        TreeNode cur=root;
        TreeNode prev=cur;
        while(cur!=null){
            if(cur.val<key) {
                prev=cur;
                cur = cur.right;
            } else if (cur.val>key) {
                prev=cur;
                cur=cur.left;
            }else{
                remove(prev,cur);
            }
        }
    }
    public void remove(TreeNode prev,TreeNode cur){
        if(cur.left==null){
            if(cur==root){
                root=cur.right;
            } else if (prev.left==cur) {
                    prev.right=cur.right;
            }else{
                 prev.right=cur.right;
            }
        } else if (cur.right==null) {
            if(cur.right==root){
                root=cur.right;
            } else if (prev.right==cur) {
                prev.right=cur.left;
            }else{
                prev.left=cur.left;
            }
        }else{
            TreeNode targetPrev=cur;
            TreeNode target=cur.right;
           while(target.left!=null){
               targetPrev=target;
               target=target.left;
           }
           cur.val= target.val;
           if(targetPrev.left==target){
               targetPrev.left=target.right;
           }else{
               targetPrev.right=target.right;
           }
        }
    }
}
